package cn.qyl.joha.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;

/*
 * 随机验证码工具类
 * 1.生成4个随机数的字符串
 * 2.根据4个随机数绘制验证码图片
 */
public class AuthCode {
	
	static Random random = new Random();
	public static String getRandomNum(){
		ArrayList<Object> code = new ArrayList<Object>();
		ArrayList<Object> newcode = new ArrayList<Object>();
		
		for(char i =65; i<90;i++){
			code.add(i);
		}
		for(char i=97;i<122;i++){
			code.add(i);
		}
		for(int i=0;i<10;i++){
			code.add(i);
		}
		StringBuilder sb = new StringBuilder();
/*		for(int i=0;i<4;i++){
			int num  = random.nextInt(10);
			code.append(num+"");
		}*/
		
		for(int j = 0;j<4;j++){
			int num = random.nextInt(code.size());
			newcode.add(num);
			sb.append(code.get(num));
		}
		return sb.toString();
	}
	
	
	//根据随机数生成验证码图片
	public static BufferedImage getAuthCodeImg(String code){
		
		//绘制画布
		BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);
		//绘制画笔
		Graphics graphics = image.getGraphics();
		//设置画布背景颜色
		graphics.setColor(Color.YELLOW);
		//填充矩形
		graphics.fillRect(0, 0, 100, 40);
		//设置字体颜色
		graphics.setColor(Color.BLACK);
		//设置字体样式
		graphics.setFont(new Font("宋体", Font.BOLD, 20));
		//把随机数循环绘制到画布中
		for(int i = 0; i<code.length(); i++){
			//charAt(index) : 根据索引值获取该字符串的字符
			char c = code.charAt(i);
			
			graphics.drawString(c+"", 20*i+5, 16);
		}
		//绘制干扰线(5条干扰线)
		for(int i=0;i<5;i++){
			//在画布中绘制干扰线
			//一条干扰线具备A点(x1,y1)与B点(x2,y2)相连
			int x1 = random.nextInt(88);
			int y1 = random.nextInt(28);
			int x2 = random.nextInt(88);
			int y2 = random.nextInt(28);
			graphics.drawLine(x1, y1, x2, y2);
			graphics.drawLine(x1, y1, x2, y2);
			}

		return image;
	}
	
	

}
